<?php
html::printPath(array(
	    'seminar.form-title' => 'admin/seminar/all',
	    $seminar['name'] => '/admin/seminar/display?id=' . $seminar['id'],
		'seminar.accommodation-title' => '/admin/seminarAccomodation/overview',
	    'seminar.assignAccomodation-title' => ''
	),
	'seminar-assignAccomodation-desc'
);
$msg->printMessages();

// TODO remove i18n keys
//$selectedBatchText = text::get('seminar.selectBatch');
//$selectedAccomodationText = text::get('seminar.selectAccomodationType');

echo '<div style="overflow:auto;">';
echo '<table class="displayTable" style="float: left">';
echo '<tbody>';
echo '<tr><th>' . text::getEscaped('seminarAccomodation-selectedBatch') . '</th><td>' . $seminarBatch['name'] . '</td></tr>';
echo '<tr><th>' . text::getEscaped('seminarAccomodation-selectedAccomodationType') . '</th><td>' . $accomodationType['name'] . '</td></tr>';
echo '<tr><th>' . text::getEscaped('person-gender') . '</th><td>' . text::getEscaped('person-gender-' . $this->data->gender) . '</td></tr>';
// echo '<tr><td></td><td>' . '<p class="description">' . html::popup('/admin/seminarAccomodation/settingsForm', text::get('seminarAccomodation.settings')) . '</p></td></tr>';
echo '</tbody>';
echo '</table>';

echo '<span class="description" style="float: left; margin: 5px 0 0 24px;">' . html::popup('/admin/seminarAccomodation/settingsForm', text::get('seminarAccomodation.settings')) . '</span>';
echo '</div>';

// List type
// - rooms (drag & drop)
// - registrations - group by country, order by age, registrations with no room unassigned are listed on the bottom

function writeTable($tableUuid, $registrationList, $roomOptions) {
    if ($registrationList) {
        $elb = new EntityListBuilder('registration', $registrationList);
        $elb->setUuid($tableUuid);
        $elb->checkbox('registration_ids[]', 'id')->noLink();
        $elb->integer('id')->linkWithValue('/admin/registration/display?id=', 'id');
        $elb->text('person_id')->doubleValue('last_name', 'first_name')->alignLeft()->orderByField('last_name')->linkWithValue('/admin/person/display?id=', 'person_id');
        $elb->date('birth_date')->labelKey('person.birth_date');
        $elb->text('country_name')->labelKey('person.country_of_residence_code');
        // $elb->timestamp('created_at');
        $elb->longText('payment_organization_name')->labelKey('registration.payment_organization_id');
        $elb->longText('org_notes');
        $elb->longText('program_notes');
        // $elb->autocomplete('room_code', $roomOptions, 'onchange="changeRoom(this)"')->addNameSuffix('id');
        $elb->combobox('room_code', $roomOptions, 'onchange="changeRoom(this)"')->addNameSuffix('id');
        $elb->write();
    }
}

function writeReadOnlyTable($tableUuid, $registrationList, $roomOptions) {
    $elb = new EntityListBuilder('registration', $registrationList);
    $elb->setUuid($tableUuid);
    $elb->integer('id')->linkWithValue('/admin/registration/display?id=', 'id');
    $elb->text('person_id')->doubleValue('last_name', 'first_name')->alignLeft()->orderByField('last_name')->linkWithValue('/admin/person/display?id=', 'person_id');
    // $elb->timestamp('created_at');
    $elb->text('batch_code')->valueFunction(batchInfo);
    $elb->date('birth_date')->labelKey('person.birth_date');
    $elb->text('country_name')->labelKey('person.country_of_residence_code');
    $elb->longText('org_notes');
    $elb->text('room_name')->labelKey('room_code');
    $elb->write();
}

function batchInfo($entity) {
    return '<span title="' . format::dateInterval($entity['begin_date'], $entity['end_date']) . '">' . html::escape($entity['batch_name']) . '</span>';
}

echo form::open('/admin/seminarAccomodation/assignSelected');

echo '<h3>' . text::getEscaped('seminarAccomodation.withoutAccomodation') . ' <span style="font-weight:normal">(' . count($registrationList) . ')</span></h3>';
// echo 'Secondary sort column: ' . form::comboBox('secondaryOrder', array('age' => 'Age', 'country' => 'Country', 'name' => 'Name', 'registrationDate' => 'Registration date'), $formData);
writeTable($this->REGISTRATION_LIST_UUID, $registrationList, $roomOptions);

if ($roomList) {
    foreach ($roomList as $room) {
        $personCount = 0;
        if ($room['registrationList']) {
            $personCount += count($room['registrationList']);
        }
        if ($room['registrationListFromOverlappingBatches']) {
            $personCount += count($room['registrationListFromOverlappingBatches']);
        }
        if ($room['registrationListOfOtherGender']) {
        	$personCount += count($room['registrationListOfOtherGender']);
        }
        
        if ($personCount == 0) {
        	continue;
        }
        
        echo '<h3>' . $room['name'] . ' <span style="font-weight:normal">(' . $personCount . ' / ' . $room['capacity'] . ')</span>' . '</h3>';
        
        // Colour the room to indicate how full it is
        $roomClass = 'accRoom-';
        $fullness = $personCount / $room['capacity'];
        if ($fullness < 0.75) {
            $roomClass .= 'enoughSpace';
        }
        else if ($fullness < 1) {
            $roomClass .= 'almostFull';
        }
        else if ($fullness == 1) {
            $roomClass .= 'full';
        }
        else {
            $roomClass .= 'crowded';
        }
            
        echo '<div class="' . $roomClass . '">';
        if ($room['registrationList']) {
            writeTable($this->REGISTRATION_LIST_UUID . '-' . $room['code'], $room['registrationList'], $roomOptions);
        }
        if ($room['registrationListFromOverlappingBatches']) {
            writeReadOnlyTable($this->REGISTRATION_LIST_UUID . '-' . $room['code'] . '-over', $room['registrationListFromOverlappingBatches'], $roomOptions);
        }
        if ($room['registrationListOfOtherGender']) {
        	writeReadOnlyTable($this->REGISTRATION_LIST_UUID . '-' . $room['code'] . '-gender', $room['registrationListOfOtherGender'], $roomOptions);
        }
        echo '</div>';
    }
}

echo text::getEscaped('seminarAccomodation.moveSelectedToRoom') . ': ' . form::comboBox('room_code', form::addEmptyOption($roomOptions), array());

// echo form::submitButton('save');

echo form::close();
?>

<script type="text/javascript">
    function changeRoom(combobox) {
        var $checkbox = $(combobox).closest('tr').find('input[name="registration_ids[]"]');
        var registrationId = $checkbox.attr('value');
        var roomCode = combobox.value;
        var seminarId = <?php echo $seminar['id'] ?>;
        var batchCode = '<?php echo $seminarBatch['batch_code'] ?>';
        var accomodationTypeCode = '<?php echo $accomodationType['code'] ?>';

        var url = 'assignOne?id=' + seminarId + '&batch_code=' + batchCode + '&accomodation_type_code=' + accomodationTypeCode + '&registration_id=' + registrationId + '&room_code=' + roomCode;
        // replacePageByAjax(url, null);
        // document.location.href = url;
        Yosemin.Ajax.partialPageUpdate(url, null, null, null);
    }

    $(document).ready(function() {
        /**
         * Selecting rows by clicking on them.
         */
        $('.listTable > tbody > tr').click(function (event) {
            if (! event.target.tagName.match(/A|SELECT|OPTION/)) {
                var $row = $(event.target).closest('tr');
                var $checkbox = $row.find(':checkbox');
                if ($checkbox.size() > 0) {
	                if (event.target.tagName != 'INPUT') {
	                	$checkbox.get(0).checked = ! $checkbox.get(0).checked;
	                }
	                if ($row.hasClass('selectedRow')) {
	                	$row.removeClass('selectedRow');
	                }
	                else {
	                	$row.addClass('selectedRow');
	                }
                }
            }
        });

        var effectedIdString = '<?php echo $effectedIds; ?>';
        if (effectedIdString) {
        	var effectedIds = effectedIdString.split(",");
        	for (var i = 0; i < effectedIds.length; i++) {
	            $('input[value=' + effectedIds[i] + ']').closest('tr')
	            	.css('background-color', '#AAFF00')
	            	.animate({
	            		'background-color': '#FFFFFF'
	              	}, 2000, function() {$(this).css('background-color', '')});
        	}
        }

        $('#room_code').change(function(event) {
            var $form = $(event.target).closest('form');
            Yosemin.Ajax.partialPageUpdate(null, $form.get(0), null, null);
        });
    });
</script>